Skip to content

Conversation

pavlips
Copy link

@pavlips pavlips commented Sep 15, 2025

In some cases, elementwise fusion can produce ops with multiple results, but only one of them is used in the IR. This makes the IR less readable and prevents additional fusions from being triggered.

This patch adds the DropRedundantResultsFromGenericOps pattern to find these outputs and convert them into inputs.

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Sep 15, 2025

@llvm/pr-subscribers-mlir-linalg

@llvm/pr-subscribers-mlir

Author: Pavel Lipskiy (pavlips)

Changes

In some cases, elementwise fusion can produce ops with multiple results, but only one of them is used in the IR. This makes the IR less readable and prevents additional fusions from being triggered.

This patch adds the DropRedundantResultsFromGenericOps pattern to find these outputs and convert them into inputs.


Full diff: https://github.com/llvm/llvm-project/pull/158627.diff

2 Files Affected:

  • (modified) mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp (+51)
  • (modified) mlir/test/Dialect/Linalg/fusion-elementwise-ops.mlir (+22-1)
diff --git a/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp b/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp
index 3bd763ea00cd7..aac54327213ac 100644
--- a/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp
+++ b/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp
@@ -2200,6 +2200,56 @@ struct RemoveOutsDependency : public OpRewritePattern<GenericOp> {
   }
 };
 
+/// Drops an unused result from an elementwise `linalg.generic` by
+/// reclassifying its tied `outs` operand as an extra input operand.
+struct DropRedundantResultsFromGenericOps
+    : public OpRewritePattern<linalg::GenericOp> {
+  using OpRewritePattern<linalg::GenericOp>::OpRewritePattern;
+  LogicalResult matchAndRewrite(linalg::GenericOp op,
+                                PatternRewriter &rewriter) const override {
+    if (!linalg::isElementwise(op) || op.getNumResults() < 2U)
+      return failure();
+    // Given that the op has no reductions, there is no need to preserve an
+    // unused result: transform it into an input instead.
+    auto maybeUnusedRes = llvm::find_if(
+        op.getResults(), [](OpResult res) { return res.use_empty(); });
+    if (maybeUnusedRes == op.getResults().end())
+      return failure();
+    OpResult unusedRes = *maybeUnusedRes;
+    const unsigned resIdx = unusedRes.getResultNumber();
+    auto resTypes = llvm::to_vector(op.getResultTypes());
+    resTypes.erase(resTypes.begin() + resIdx);
+    SmallVector<Value> resValues = llvm::to_vector_of<Value>(op.getResults());
+    resValues.erase(resValues.begin() + resIdx);
+    const int64_t numInputs = op.getNumDpsInputs();
+    OpOperand *resOperand = op.getTiedOpOperand(unusedRes);
+    AffineMap map = op.getIndexingMapMatchingResult(unusedRes);
+    const unsigned operandIdx = resOperand->getOperandNumber();
+    // Remove the output operand and add it as an input operand with the same
+    // map.
+    SmallVector<Value> outs(op.getOutputs());
+    outs.erase(outs.begin() + resIdx);
+    SmallVector<Value> ins(op.getInputs());
+    ins.insert(ins.begin() + numInputs, resOperand->get());
+    SmallVector<AffineMap> maps = op.getIndexingMapsArray();
+    maps.erase(maps.begin() + operandIdx);
+    maps.insert(maps.begin() + numInputs, map);
+    rewriter.setInsertionPoint(op);
+    auto newGenericOp = rewriter.create<linalg::GenericOp>(
+        op.getLoc(), TypeRange(resTypes), ins, outs, maps,
+        op.getIteratorTypesArray());
+    op->setDiscardableAttrs(op->getDiscardableAttrDictionary());
+    op.getBody()->getTerminator()->eraseOperands(resIdx);
+    newGenericOp.getRegion().takeBody(op.getBodyRegion());
+    // Replace the remaining results of the old op with the results of the new
+    // op.
+    rewriter.replaceAllUsesWith(resValues, newGenericOp.getResults());
+    // Remove the old op.
+    rewriter.eraseOp(op);
+    return success();
+  }
+};
+
 /// Fold linalg.fill into linalg.generic
 struct FoldFillWithGenericOp : public OpRewritePattern<GenericOp> {
   using OpRewritePattern<GenericOp>::OpRewritePattern;
@@ -2262,6 +2312,7 @@ void mlir::linalg::populateElementwiseOpsFusionPatterns(
                RemoveOutsDependency>(context);
   // Add the patterns that clean up dead operands and results.
   populateEraseUnusedOperandsAndResultsPatterns(patterns);
+  patterns.add<DropRedundantResultsFromGenericOps>(context);
 }
 
 void mlir::linalg::populateCollapseDimensions(
diff --git a/mlir/test/Dialect/Linalg/fusion-elementwise-ops.mlir b/mlir/test/Dialect/Linalg/fusion-elementwise-ops.mlir
index bc55c12c02f29..173ec8a8a5f38 100644
--- a/mlir/test/Dialect/Linalg/fusion-elementwise-ops.mlir
+++ b/mlir/test/Dialect/Linalg/fusion-elementwise-ops.mlir
@@ -1079,4 +1079,25 @@ module {
 // CHECK-NOT:     linalg.generic
 // CHECK:         tensor.expand_shape
 // CHECK:         linalg.generic {{.*}}, iterator_types = ["parallel", "parallel", "parallel", "parallel", "parallel", "parallel", "reduction"]}
-// CHECK-SAME:     ins(%[[ARG0]], %[[FUSED]]#1 : tensor<1x1x2x1xf32>, tensor<4x1x1x1xf32>)
\ No newline at end of file
+// CHECK-SAME:     ins(%[[ARG0]], %[[FUSED]]#1 : tensor<1x1x2x1xf32>, tensor<4x1x1x1xf32>)
+
+// -----
+// CHECK-LABEL: @drop_unused_results
+// CHECK-SAME:   [[ARG0:%[a-zA-Z0-9]+]]: tensor<64xf32>, [[ARG1:%[a-zA-Z0-9]+]]: tensor<1x56x56x64xf32>
+func.func @drop_unused_results(%arg0: tensor<64xf32>, %arg1: tensor<1x56x56x64xf32>) -> tensor<1x56x56x64xf32> {
+  %cst = arith.constant 3.40282347E+38 : f32
+  %cst_0 = arith.constant 0.000000e+00 : f32
+  // CHECK: [[OUT:%[a-zA-Z0-9]+]] = tensor.empty() : tensor<1x56x56x64xf32>
+  %0 = tensor.empty() : tensor<1x56x56x64xf32>
+  // CHECK: [[RES:%[0-9]+]] = linalg.generic {{.*}} ins([[ARG0]], [[ARG1]] : tensor<64xf32>, tensor<1x56x56x64xf32>) outs([[OUT]] : tensor<1x56x56x64xf32>)
+  %1:2 = linalg.generic {indexing_maps = [affine_map<(d0, d1, d2, d3) -> (d3)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>], iterator_types = ["parallel", "parallel", "parallel", "parallel"]} ins(%arg0 : tensor<64xf32>) outs(%arg1, %0 : tensor<1x56x56x64xf32>, tensor<1x56x56x64xf32>) {
+  ^bb0(%in: f32, %out: f32, %out_1: f32):
+    %2 = arith.addf %in, %out : f32
+    %3 = arith.minimumf %2, %cst : f32
+    %4 = arith.maximumf %3, %cst_0 : f32
+    linalg.yield %2, %4 : f32, f32
+  } -> (tensor<1x56x56x64xf32>, tensor<1x56x56x64xf32>)
+  // CHECK: -> tensor<1x56x56x64xf32>
+  // CHECK: return [[RES]] : tensor<1x56x56x64xf32>
+  return %1#1 : tensor<1x56x56x64xf32>
+}

Copy link
Contributor

@MaheshRavishankar MaheshRavishankar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

void mlir::linalg::populateEraseUnusedOperandsAndResultsPatterns(
should take care of this for you.

@pavlips
Copy link
Author

pavlips commented Sep 16, 2025

Hey @MaheshRavishankar , thanks for taking a look!

From my rough understanding populateEraseUnusedOperandsAndResultsPatterns erases outs[i] and its result only when the result is dead and the tied out’s block-arg is unused in the payload or only in linalg.yield with the correct index.

After fusion, there are cases where the payload still reads that tied block-arg to build another live result, but the corresponding result is unused. In that situation the pattern doesn’t fire; the op retains the outs[i]/result pair, which prevents further fusion and harms readability.

This patch reclassifies that outs[i] as an input and drops the corresponding result (not erases them). The @drop_unused_results test demonstrates the case where the existing pattern doesn't fire.

I hope this is more of a clear explanation; please let me know if something is confusing.

Copy link
Contributor

@nirvedhmeshram nirvedhmeshram left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes sense to me, but I have a question about a possible corner case, with the region we are making

In some cases, elementwise fusion can produce ops with multiple
results, but only one of them is used in the IR. This makes the
IR less readable and prevents additional fusions from being triggered.

This patch adds the `DropRedundantResultsFromGenericOps` pattern
to find these outputs and convert them into inputs.

Signed-off-by: Pavel Lipskiy <pavel.lipskiy@arm.com>
Copy link

⚠️ C/C++ code formatter, clang-format found issues in your code. ⚠️

You can test this locally with the following command:
git-clang-format --diff origin/main HEAD --extensions cpp -- mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp

⚠️
The reproduction instructions above might return results for more than one PR
in a stack if you are using a stacked PR workflow. You can limit the results by
changing origin/main to the base branch/commit you want to compare against.
⚠️

View the diff from clang-format here.
diff --git a/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp b/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp
index f27175a1f..95eda34a7 100644
--- a/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp
+++ b/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp
@@ -2227,7 +2227,7 @@ struct DropRedundantResultsFromGenericOps
     OpOperand *resOperand = op.getTiedOpOperand(unusedRes);
     AffineMap map = op.getIndexingMapMatchingResult(unusedRes);
     const unsigned operandIdx = resOperand->getOperandNumber();
-    
+
     // Remove the output operand and add it as an input operand with the same
     // map.
     SmallVector<Value> outs(op.getOutputs());
@@ -2250,7 +2250,7 @@ struct DropRedundantResultsFromGenericOps
     // Replace the remaining results of the old op with the results of the new
     // op.
     rewriter.replaceAllUsesWith(resValues, newGenericOp.getResults());
-    
+
     // Remove the old op.
     rewriter.eraseOp(op);
     return success();

// CHECK: [[OUT:%[a-zA-Z0-9]+]] = tensor.empty() : tensor<1x56x56x64xf32>
%0 = tensor.empty() : tensor<1x56x56x64xf32>
// CHECK: [[RES:%[0-9]+]] = linalg.generic {{.*}} ins([[ARG0]], [[ARG1]] : tensor<64xf32>, tensor<1x56x56x64xf32>) outs([[OUT]] : tensor<1x56x56x64xf32>)
%1:2 = linalg.generic {indexing_maps = [affine_map<(d0, d1, d2, d3) -> (d3)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>], iterator_types = ["parallel", "parallel", "parallel", "parallel"]} ins(%arg0 : tensor<64xf32>) outs(%arg1, %0 : tensor<1x56x56x64xf32>, tensor<1x56x56x64xf32>) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This input in theory is wrong. I understand your pattern is making the semantics of the operation "right". But for an operation with all parallel iterator types, you cannot read the out value. If you are doing that then this has to be a reduction.
I would put this input operation as having "undefined" behavior and therefore "fixing" the benhavior does not make sense either. This should be fixed on the lowering itself.

We could make this explicitly a verifier error as well.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well having said that, there is a pattern populateMoveInitOperandsToInput that already seems to do some of this. Maybe if you run that "before" your pass it will fix the issue for you. I think that pattern was added explicitly to fix such "ill-defined" operations.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[taking over Pavel whose internship is now finished]

Ack. This pattern was the result of some tensor fusion pattern, but I need to investigate if it's an upstream pattern or not. I've put this PR as draft for the time being while I check whether it was an upstream pattern that caused this invalid IR. All I know is we seem to call populateMoveInitOperandsToInput implicitely via LinalgFoldUnitExtentDimsPass but when removing the pattern added by this patch we get worse code generation. I'll update once we've found the root cause. Thanks for the review so far!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MaheshRavishankar where is the documentation that this IR is invalid? I couldn't find something in the online Linalg dialect documentation about out being read-only for parallel-only iterator maps. Is there a verifier that checks that?

@MaheshRavishankar
Copy link
Contributor

After fusion, there are cases where the payload still reads that tied block-arg to build another live result, but the corresponding result is unused. In that situation the pattern doesn’t fire; the op retains the outs[i]/result pair, which prevents further fusion and harms readability.

Yeah, I thought that might be what you are trying to fix, but I think the input is wrong, and the semantics of the input is unclear, so any transformation on those kind of operations is sketchy.

Copy link
Contributor

@nirvedhmeshram nirvedhmeshram left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, looks like there are formatting issues (trailing whitespaces perhaps?), I usually use

git clang-format HEAD^

to have the code formatted correctly. But after that's fixed i think this is good.

Copy link
Contributor

@nirvedhmeshram nirvedhmeshram left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After reading @MaheshRavishankar 's review on the input validity, perhaps we want to rethink this pattern.

@RoboTux RoboTux marked this pull request as draft September 23, 2025 09:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants